import {useEffect, useState} from "react"
import {CityData} from "types/user"
import CitysData from "../res/citys.json"
import {Coords, locationManager} from "../utils/location"
import {Alert} from "react-native"
import {useDispatch} from "react-redux"
import {toggle, toggleConfirm, toggleToast} from "../store/system/systemSlice"
import {THConfirmModalProps} from "../components/THModel"
export const useDate = () => {
  // 日期选择器所需的日期数据
  const YEARS = Array.from({length: 50}, (_, i) =>
    (new Date().getFullYear() - 50 + i).toString(),
  )
  const MONTHS = Array.from({length: 12}, (_, i) =>
    (i + 1).toString().padStart(2, "0"),
  )
  const DAYS = Array.from({length: 31}, (_, i) =>
    (i + 1).toString().padStart(2, "0"),
  )
  return {YEARS, MONTHS, DAYS}
}

// 导出城市数据hooks
export const useCityData = () => {
  const [cityData, setCityData] = useState<CityData>([])
  const [provinceList, setProvinceList] = useState<string[]>([]) // 省份列表
  const [cityList, setCityList] = useState<string[]>([]) // 城市列表
  const [areaList, setAreaList] = useState<string[]>([]) // 区域列表
  const [currentProvince, setCurrentProvince] = useState("") // 当前选择城市
  const [currentCity, setCurrentCity] = useState("") // 当前选择城市
  const [currentArea, setCurrentArea] = useState("") // 当前选择区域

  useEffect(() => {
    const data = CitysData as any[]
    setCityData(data)
    const provinces: string[] = data.map(item => Object.keys(item)[0])
    setProvinceList(provinces)
    if (provinces.length > 0) {
      setCurrentProvince(provinces[0])
    }
  }, [])

  useEffect(() => {
    if (!currentProvince || cityData.length === 0) {
      setCityList([])
      setAreaList([])
      return
    }

    const currentProvinceData = cityData.find(
      item => Object.keys(item)[0] === currentProvince,
    )
    if (currentProvinceData) {
      const citiesOfProvince = currentProvinceData[currentProvince] || []
      const cities: string[] = citiesOfProvince.map(
        (item: any) => Object.keys(item)[0],
      )
      setCityList(cities)
      if (cities.length > 0) {
        setCurrentCity(cities[0])
      } else {
        setCurrentCity("")
      }
    }
  }, [currentProvince, cityData])

  useEffect(() => {
    if (!currentCity || cityData.length === 0) {
      setAreaList([])
      return
    }

    const currentProvinceData = cityData.find(
      item => Object.keys(item)[0] === currentProvince,
    )
    if (currentProvinceData) {
      const citiesOfProvince = currentProvinceData[currentProvince] || []
      const currentCityData = citiesOfProvince.find(
        (item: any) => Object.keys(item)[0] === currentCity,
      )

      if (currentCityData) {
        const areas = currentCityData[currentCity] || []
        setAreaList(areas)
        if (areas.length > 0) {
          setCurrentArea(areas[0])
        } else {
          setCurrentArea("")
        }
      }
    }
  }, [currentCity, currentProvince, cityData])

  // 切换省份数据
  const changeProvince = (province: string) => {
    setCurrentProvince(province)
  }
  // 切换城市数据
  const changeCity = (city: string) => {
    setCurrentCity(city)
  }

  const changeArea = (area: string) => {
    setCurrentArea(area)
  }

  return {
    provinceList,
    cityList,
    areaList,
    currentArea,
    currentCity,
    currentProvince,
    changeProvince,
    changeCity,
    changeArea,
  }
}

export const useLocation = () => {
  const [currentAddress, setCurrrentAddress] = useState("")
  const [currentLocation, setCurrentLocation] = useState<Coords>({} as Coords)
  // 使用高德地图地位
  useEffect(() => {
    resetLocaiton()
  }, [])
  const resetLocaiton = async () => {
    try {
      await locationManager.initGeo()
      const location = await locationManager.getCurrentPosition()
      const res = await locationManager.getCityByLocation()
      setCurrrentAddress(res)
      setCurrentLocation(location)
    } catch (error) {
      Alert.alert((error as any).message)
    }
  }
  return {currentAddress, resetLocaiton, currentLocation}
}

export const useShowToast = () => {
  const dispatch = useDispatch()
  return (text: string) => dispatch(toggleToast({show: true, text}))
}
export const useShowConfirm = () => {
  const dispatch = useDispatch()

  return (options: THConfirmModalProps) => {
    const onConfirm = async () => {
      if (options.onConfirm) {
        await options.onConfirm()
      }
      dispatch(toggleConfirm({...options, isVisible: false}))
    }
    const onCancel = async () => {
      if (options.onCancel) {
        await options.onCancel()
      }
      dispatch(toggleConfirm({...options, isVisible: false}))
    }
    dispatch(
      toggleConfirm({
        ...options,
        isVisible: true,
        onConfirm,
        onCancel,
      }),
    )
  }
}
export const useLoading = () => {
  const dispatch = useDispatch()
  return () => {
    dispatch(toggle(true))
    return () => dispatch(toggle(false))
  }
}
